'''
Created on Apr 20, 2010

@author: darkelf
'''
import xml.dom.minidom
from basic.html_objects import *
from xml.dom.minidom import Node
from string import whitespace

class DMLParser:
    
    def __init__(self):
        self.html_page = None
    
    def parse_dml_file(self, dml_path):        
        dml_file =  xml.dom.minidom.parse(dml_path)
        
        dml_root = dml_file.getElementsByTagName("BasicHtmlPage")
        
        if len(dml_root) == 1:
            self.html_page = BasicHtmlPage()            
            for node in dml_root[0].childNodes:                
                if node.nodeType == Node.ELEMENT_NODE:
                    object = self.get_object(node.nodeName)
                    self.html_page.body_elements.append(object)
                    self.append_childs(object, node)
                    n_attributes = node.attributes
                    
                    a = 0
                    while a < n_attributes.length:
                        item = n_attributes.item(a)
                        object.__getattribute__("set_"+item.name)(item.value)
                        a+=1                                    
        else:
            print "Invalid DML file! Expected 1 BasicHtmlPage tag, but " + len(dml_root) + " found."
        return self.html_page
    
    def append_childs(self,object,node):
        n_attributes = node.attributes                    
        a = 0
        while a < n_attributes.length:
            item = n_attributes.item(a)
            object.__getattribute__("set_"+item.name)(item.value)
            a+=1
        for ch_node in node.childNodes:
            if ch_node.nodeType == Node.ELEMENT_NODE:
                ch_object = self.get_object(ch_node.nodeName)
                object.childs.append(ch_object)
                self.append_childs(ch_object, ch_node)
            elif ch_node.nodeType == Node.TEXT_NODE:
                if isinstance(object, BasicHtmlText):
                    object.set_content(ch_node.data)                    
    
    def get_object(self,object_name):
        _class = globals()[object_name]
        return _class()